package com.agrimall.util;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * 数据库工具类
 * 使用C3P0连接池管理数据库连接
 */
public class DBUtil {
    private static DataSource dataSource;
    
    static {
        try {
            // 加载数据库配置
            InputStream is = DBUtil.class.getClassLoader().getResourceAsStream("db.properties");
            Properties props = new Properties();
            props.load(is);
            
            // 创建C3P0数据源
            ComboPooledDataSource cpds = new ComboPooledDataSource();
            cpds.setDriverClass(props.getProperty("jdbc.driver"));
            cpds.setJdbcUrl(props.getProperty("jdbc.url"));
            cpds.setUser(props.getProperty("jdbc.username"));
            cpds.setPassword(props.getProperty("jdbc.password"));
            
            // 连接池配置
            cpds.setInitialPoolSize(Integer.parseInt(props.getProperty("c3p0.initialPoolSize", "5")));
            cpds.setMaxPoolSize(Integer.parseInt(props.getProperty("c3p0.maxPoolSize", "20")));
            cpds.setMinPoolSize(Integer.parseInt(props.getProperty("c3p0.minPoolSize", "5")));
            cpds.setMaxIdleTime(Integer.parseInt(props.getProperty("c3p0.maxIdleTime", "300")));
            cpds.setAcquireIncrement(Integer.parseInt(props.getProperty("c3p0.acquireIncrement", "5")));
            
            dataSource = cpds;
        } catch (Exception e) {
            throw new RuntimeException("数据库初始化失败", e);
        }
    }
    
    /**
     * 获取数据库连接
     */
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }
    
    /**
     * 获取数据源
     */
    public static DataSource getDataSource() {
        return dataSource;
    }
}



